package com.dushiguang.findhoney.BaiduMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;

import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.dushiguang.findhoney.R;
import com.dushiguang.findhoney.Utils.Iconfont.SetIconFont;
import com.dushiguang.findhoney.View.RadarView.SearchDevicesView;


import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ex-dushiguang201 on 2015-10-30.
 */
@EActivity(R.layout.activity_baidumap)
public class MyBaiduMap extends Activity implements OnMapStatusChangeListener{
    @ViewById(R.id.button_search)
    Button button_search;
    // 百度地图控件
    private MapView mMapView = null;
    private com.baidu.mapapi.map.BaiduMap mBaiduMap;
    private BitmapDescriptor mCurrentMarker;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    public MyLocationListener mMyLocationListener;
    //POI搜索
    private MyOverlayManager mTrafficOverLay;// 交通图层
    private MyOverlayManager mSchoolOverLay;// 学校图层
    private MyOverlayManager mLiveOverLay;// 生活图层
    private PoiSearch mPoiSearch;//搜索服务
    private float latitude = 31.1803029f;
    private float longitude = 121.4864084f;

    /***
     * 是否是第一次定位
     */
    private volatile boolean isFristLocation = true;
    /**
     * 定位的客户端
     */
    private LocationClient mLocationClient;
    private BDLocation mBdLocation;

    @ViewById(R.id.find_location_iv)
    ImageView mImageView;
    @ViewById(R.id.search_device_view)
    SearchDevicesView search_device_view;
    @ViewById(R.id.start_search_tv)
    TextView mStartSearch;
    @ViewById(R.id.search_device_view)
    SearchDevicesView searchDevice;

    @Extra("Longitude")
    Double mLongitude;
    @Extra("Latitude")
    Double mLatitude;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        /*
         * 这里需要注意一下：initialize方法中必须传入的是ApplicationContext，传入this，
         * 或者MAinActivity.this都不行，不然会报运行时异常，所以百度建议把该方法放到Application的初
         * 始化方法中。
         */
        SDKInitializer.initialize(getApplicationContext());
    }

    @AfterViews
    void init() {
        search_device_view.setWillNotDraw(false);
        SetIconFont.initIconFont(this, mStartSearch);
        initBaiduMap();
    }

    public void initBaiduMap() {
        mMapView = (MapView) findViewById(R.id.bmapview);
        /**
         * mCurrentMode = LocationMode.FOLLOWING; // 跟随模式
         * mCurrentMode = LocationMode.COMPASS; // 罗盘模式
         */
        mMyLocationListener = new MyLocationListener();
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL; // 普通模式LocationMode
        //mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.ic_location); // 自定义图标
        mBaiduMap = mMapView.getMap();

        mBaiduMap.setOnMapStatusChangeListener(this);
        mBaiduMap.setMyLocationEnabled(true);//设置是否允许定位图层
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(mMyLocationListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);//打开GPS
        /**
         * setCoorType坐标类型分为三种：
         * bd09ll百度加密经纬度坐标
         * bd09百度加密墨卡托坐标
         * gcj02国测局加密经纬度坐标
         */
        option.setCoorType("bd0911");//设置坐标类型
        option.setScanSpan(5000);//定位时间间隔（ms）
        mLocationClient.setLocOption(option);
        mLocationClient.start();

        mTrafficOverLay = new MyOverlayManager(mBaiduMap);
        mSchoolOverLay = new MyOverlayManager(mBaiduMap);
        mLiveOverLay = new MyOverlayManager(mBaiduMap);

        checkSearchParam();//初始化POI
        //如何自定义图标???


        BaiduMapOptions mapOptions = new BaiduMapOptions();
    }

    @Override
    public void onMapStatusChangeStart(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChange(MapStatus mapStatus) {

    }

    @Override
    public void onMapStatusChangeFinish(MapStatus mapStatus) {

    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            mBdLocation = bdLocation;
            // MapView 销毁后不在处理新接收的位置
            if (bdLocation == null || mMapView == null) {
                return;
            }
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(0).latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            // 设置自定义图标
            mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
            // 第一次定位时，将地图位置移动到当前位置
            if (isFristLocation) {
                isFristLocation = false;
                LatLng ll = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
            showOtherLocation ();
            //showTextOverlay();
        }
    }

    private void showOtherLocation () {
        Log.e("dushiguang", "showOtherLocation" + mLongitude + "===" + mLatitude);
        //定义Maker坐标点
        LatLng point = new LatLng(latitude,longitude);
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ic_thumb);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }

    private void showTextOverlay() {
        //文字，在地图中也是一种覆盖物，开发者可利用相关的接口，快速实现在地图上书写文字的需求。实现方式如下：
        //定义文字所显示的坐标点
        LatLng llText = new LatLng(latitude,longitude);
        //构建文字Option对象，用于在地图上添加文字
        OverlayOptions textOption = new TextOptions()
                .bgColor(0xAAFFFF00)
                .fontSize(50)
                .fontColor(0xFFFF00FF)
                .text("文字显示")
                .rotate(0)
                .position(llText);
        //在地图上添加该文字对象并显示
        mBaiduMap.addOverlay(textOption);
    }

    @Click(R.id.find_location_iv)
    void findLocation() {
        requestLocation();
    }

    @Click(R.id.start_search_tv)
    void startSearch() {
        if(searchDevice.getVisibility() == View.VISIBLE ){
            searchDevice.setVisibility(View.GONE);
            search_device_view.setSearching(false);
        } else {
            requestLocation();
            searchDevice.setVisibility(View.VISIBLE);
            search_device_view.setSearching(true);
        }
    }

    /**
     * 请求定位
     */
    private void requestLocation() {
        if (mBdLocation != null) {
            //地理坐标-->LatLng
            //latitude - 纬度
            //longitude - 经度
            LatLng ll = new LatLng(mBdLocation.getLatitude(), mBdLocation.getLongitude());
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
            mBaiduMap.animateMapStatus(u);
            Toast.makeText(this, "定位成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this,"定位失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        search_device_view.setSearching(false);
        // 退出时销毁定位
        mLocationClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }
    /**************************POI搜索*************************************************************/
    @Click(R.id.button_search)
    void poiSearch() {
        nearbySearch(1);
    }

    @Click(R.id.button_clean)
    void poiClean() {
        mLiveOverLay.removeFromMap();
    }
    /**
     * 初始化POI搜索
     */
    private void checkSearchParam() {
        if (null == mPoiSearch) {
            mPoiSearch = PoiSearch.newInstance();
            mPoiSearch.setOnGetPoiSearchResultListener(poiSearchListener);
        }
    }

    /**
     * 城市内搜索
     */
    private void citySearch(int page) {
        // 设置检索参数
        PoiCitySearchOption citySearchOption = new PoiCitySearchOption();
        citySearchOption.city("上海");// 城市
        citySearchOption.keyword("KFC");// 关键字
        citySearchOption.pageCapacity(15);// 默认每页10条
        citySearchOption.pageNum(page);// 分页编号
        // 发起检索请求
        mPoiSearch.searchInCity(citySearchOption);
    }

    /**
     * 范围检索
     */
    private void boundSearch(int page) {
        PoiBoundSearchOption boundSearchOption = new PoiBoundSearchOption();
        LatLng southwest = new LatLng(latitude - 0.01, longitude - 0.012);// 西南
        LatLng northeast = new LatLng(latitude + 0.01, longitude + 0.012);// 东北
        LatLngBounds bounds = new LatLngBounds.Builder().include(southwest)
                .include(northeast).build();// 得到一个地理范围对象
        boundSearchOption.bound(bounds);// 设置poi检索范围
        boundSearchOption.keyword("美食");// 检索关键字
        boundSearchOption.pageNum(page);
        mPoiSearch.searchInBound(boundSearchOption);// 发起poi范围检索请求
    }

    /**
     * 附近检索
     */
    private void nearbySearch(int page) {
        PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption();
        nearbySearchOption.location(new LatLng(latitude, longitude));
        nearbySearchOption.keyword("学校");
        nearbySearchOption.radius(1000);// 检索半径，单位是米
        //nearbySearchOption.pageNum(page);
        mPoiSearch.searchNearby(nearbySearchOption);// 发起附近检索请求
    }

    /**
     * POI检索监听器
     */
    OnGetPoiSearchResultListener poiSearchListener = new OnGetPoiSearchResultListener() {
        @Override
        /**
         * 搜索完毕后的回调事件,
         */
        public void onGetPoiResult(PoiResult poiResult) {
            if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {//搜索正常
                addMyOverLay(poiResult);
            } else {
                Toast.makeText(MyBaiduMap.this, "chu cuo" + poiResult.error , Toast.LENGTH_LONG).show();
            }

        }

        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
            Log.e("dushiguang","-----??");
            if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
                Toast.makeText(MyBaiduMap.this, "抱歉，未找到结果",
                        Toast.LENGTH_SHORT).show();
            } else {// 正常返回结果的时候，此处可以获得很多相关信息
                Toast.makeText(
                        MyBaiduMap.this,
                        poiDetailResult.getName() + ": "
                                + poiDetailResult.getAddress(),
                        Toast.LENGTH_LONG).show();
            }
        }
    };

    @UiThread(propagation = UiThread.Propagation.REUSE)
    void addMyOverLay(PoiResult poiResult) {
        mLiveOverLay.setData(poiResult);
        mLiveOverLay.addToMap();
        /*List<OverlayOptions> ops = new ArrayList<OverlayOptions>();
        List<PoiInfo> pois = poiResult.getAllPoi();
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ic_location);
        for(int i = 0;i < pois.size();i++){
            OverlayOptions op = new MarkerOptions().position(pois.get(i).location).icon(bitmap);
            ops.add(op);
            mBaiduMap.addOverlay(op);
        }*/

        // 缩放地图，使所有Overlay都在合适的视野内
        mLiveOverLay.zoomToSpan();
        mBaiduMap.setOnMarkerClickListener(mLiveOverLay);

    }


    /**
     * 用户poi自定义图层
     */
    class MyPoiOverlay extends PoiOverlay {
        public MyPoiOverlay(com.baidu.mapapi.map.BaiduMap arg0) {
            super(arg0);
        }

        @Override
        public boolean onPoiClick(int arg0) {
            Log.e("dushiguang","-----??--");
            super.onPoiClick(arg0);
            PoiInfo poiInfo = getPoiResult().getAllPoi().get(arg0);
            // 检索poi详细信息
            mPoiSearch.searchPoiDetail(new PoiDetailSearchOption().poiUid(poiInfo.uid));
            return true;
        }
    }

    /**
     * 覆盖物
     */
    class MyOverlayManager extends OverlayManager {
        private PoiResult poiResult = null;

        public MyOverlayManager(BaiduMap baiduMap) {
            super(baiduMap);
        }

        public void setData(PoiResult poiResult) {
            this.poiResult = poiResult;
        }

        @Override
        public boolean onMarkerClick(Marker marker) {
            if (marker.getExtraInfo() != null) {
                int index = marker.getExtraInfo().getInt("index");
                PoiInfo poi = poiResult.getAllPoi().get(index);

                // 详情搜索
                mPoiSearch.searchPoiDetail((new PoiDetailSearchOption())
                        .poiUid(poi.uid));
                return true;
            }
            return false;
        }

        @Override
        public List<OverlayOptions> getOverlayOptions() {
            if ((this.poiResult == null)
                    || (this.poiResult.getAllPoi() == null))
                return null;
            ArrayList<OverlayOptions> arrayList = new ArrayList<OverlayOptions>();
            for (int i = 1; i < this.poiResult.getAllPoi().size(); i++) {
                if (this.poiResult.getAllPoi().get(i).location == null)
                    continue;
                // 给marker加上标签
                Bundle bundle = new Bundle();
                bundle.putInt("index", i);
                arrayList.add(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(setNumToIcon(i))).extraInfo(bundle).position(this.poiResult.getAllPoi().get(i).location));
            }
            return arrayList;
        }

        /**
         * 往图片添加数字
         */
        private Bitmap setNumToIcon(int num) {
            BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_location);
            Bitmap bitmap = bd.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(bitmap);

            Paint paint = new Paint();
            paint.setColor(Color.BLACK);
            paint.setAntiAlias(true);
            int widthX;
            int heightY = 0;
            if (num < 10) {
                paint.setTextSize(30);
                widthX = 8;
                heightY = 6;
            } else {
                paint.setTextSize(20);
                widthX = 11;
            }

            canvas.drawText(String.valueOf(num),
                    ((bitmap.getWidth() / 2) - widthX),
                    ((bitmap.getHeight() / 2) + heightY), paint);
            return bitmap;
        }

        @Override
        public boolean onPolylineClick(Polyline polyline) {
            return false;
        }
    }

    /**
     * 跳转到该acitvity
     */
    public static void jumpToBaiduMap(Context context) {
        Intent intent = new Intent(context, MyBaiduMap_.class);
        context.startActivity(intent);
    }
}
